<template><!--团队排行-->
	<div id="test">
    <!--<title-top :fnlist="initObj.Fnlist"></title-top>-->
    <table-body :options="initObj"></table-body>
    <Modal v-model="scoreModal.show"
        :title="scoreModal.title"
        :mask-closable="false"
        @on-visible-change="visibleChange"
        width="400px">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="分数" prop="score">
                    <InputNumber v-model.trim="formValidate.score" :min="1" :max="1000" placeholder="输入分数"></InputNumber>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="scoreModal.show = false; scoreModal.loading = false; handleReset('formValidate')">取消</Button>
                <Button @click="saveScoreRecord('formValidate')" type="primary" :loading="scoreModal.loading">确定</Button>
            </div>
    </Modal>
    <Modal 
				v-model="scoreConfigModal"
      	title="加减分明细"
      	width="800"
      	:mask-closable = "false"
				footer-hide
      	>
				<div style="margin-bottom:10px;display: flex; justify-content: flex-end;">
					<Select filterable v-model="isAdd" placeholder="加减分"  style="width: 150px;" @on-change="getScoreConfig" clearable>
                <Option :value="1">加分</Option>
                <Option :value="2">减分</Option>
          </Select>
				</div>
				<Table border :columns="columnsScore" :data="dataScore"></Table>
				<div style="margin:10px 0px">
					<Page 
					:total=dataScoreTotal
          :page-size="dataScorePageSize"
					:current="dataScorePageIndex"
          show-total 
					show-elevator 
					@on-page-size-change="changeScorePageSize"
          @on-change="changeScorePageIndex" 
					style="text-align: end" 
					>
        </Page>
				</div>
	</Modal>
  </div>
</template>
<script>
//	import Cookies from 'js-cookie'
import {teamRankStatic,downloadSceneAllReport,addScoreRecord,teamScoreRecordAddDk,teamScoreRecordSubDk,getSubAddListDkList} from '@/api/compitionStatic'
import tableBody from './tableListComponent'
import groupMixin from "@/mixin/groupMixin"
import { getNumReg } from '@/libs/reg'

export default {
    name: 'scenes',
    props:['sceneId','poll','hlConfig','disabledAllBtn','showAction'],
    mixins: [groupMixin],
	data(){
        const a = function(val){
          this.selName = val;
          this.getRankingStatic();
        }.bind(this);
        const setName = function(val){
            this.selName = val.currentTarget.value;
        }.bind(this);
        const d = function(val){
          this.getRankingStatic(null,null,val)
        }.bind(this);
	  	return {
        addOrSubTO:{},
        teamId:'',
        scoreModal:{
            show:false,
            loading:false,
            title:'团队加分'
        },
        scoreModalDkTitle:'',
        formValidate:{
            score:1
        },
        ruleValidate:{
            score:[
                { required: true, type:'number',message: '请输入大于0的数字', trigger: 'change'},
                { validator: getNumReg(2000), trigger: 'change' }
            ]
        },
	  	  initObj:{
            Button:[
              {
                disabled: false,
                fnName: this.exportFile,
                name:'导出排行'
              },
              {
                disabled: false,
                fnName: this.exportScoreRecord,
                name:'导出得分记录'
              },
              // {
              //   disabled: false,
              //   fnName: this.downloadAllReport,
              //   name:'打包下载所有报告'
              // },
            ],
            Input:[
            ],
            Select:[
              {
                optionsValue: [],
                placeholder: '请选择团队',
                fnName: this.getRankingById
              }
            ],
            DatePicker:{
              isShow:false,
              fnName:d,
            },
            Page:{
              total:0,
              currentPage:1,
              pageSize:10
            },
            Table:{
              listCol:[
                {
//                title:'排行',
//                type: 'index',
                  align: 'center',
                  key:'rank',
//                width:60,
                  placement:'top-right',
                  order:2,
                  render:(h,params) => {
			            	let ele;
			            	if(params.row._index < 3 && this.curPage == 1){
			            		ele = h('img',{
			            			attrs:{
			            				src:require(`../../../../assets/scene/top${params.row._index+1}.png`)
			            			},
			            			style:{
			            				display:'inline-block',
//			            				width:'20px',
			            				verticalAlign: 'text-bottom',
    									marginLeft: '20px'
			            			}
			            		})
			            	}else{
			            		ele = h('span',params.row._index+1 + (this.curPage-1)*10)
			            	}
			            	let index = params.row._index+1;
			            	let color;
			            	if(index == 1){
			            		color = '#f34938';
			            	}else if(index == 2){
			            		color = '#eb8205';
			            	}else if(index == 3){
			            		color = '#27b666';
			            	}else{
			            		color = '#000'
			            	}
			            	return h('span',[
			            		h('span',{
			            			style:{
			            				color:color
			            			}
			            		},'排行'),
			            		ele
			            	]);
			            }
                },
                {
                  title:'团队名称',
                  key:'teamName',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  placement:'top-left',
                  order:1,
                    width: 220
                },
                {
                  title:'势力方名称',
                  key:'partyName',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:80,
                  show:() => this.hlConfig!=2
                },
                {
                  title:'总分',
                  key:'totalScore',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:60,
                  // render:(h,params)=>{
                  //   return h('span', params.row.totalScore.toFixed(2))
                  // }
                },
                {
                  title:'基础分',
                  key:'basicScore',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:80,
                  show:() => {
                    return this.hlConfig!=0
                  }
                },
                {
                  title:'攻击得分',
                  key:'attackScore',
                  align:'center',
                  tooltip:true,
                  width:80,
                  render:(h,params)=>{
                    return h('span', params.row.partyName=='蓝方'?'无':params.row.attackScore)
                  },
                  show:() => {
                    return this.hlConfig!=0
                  }
                },
                {
                  title:'防守失分',
                  key:'defendScore',
                  align:'center',
                  tooltip:true,
                  width:80,
                  render:(h,params)=>{
                    return h('span', params.row.partyName=='红方'?'无':params.row.defendScore)
                  },
                  show:() => {
                    return this.hlConfig!=0
                  }
                },
                {
                  title:'异常失分',
                  key:'expLoseScore',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:60,
                  render:(h,params)=>{
                    return h('span', params.row.partyName=='红方'?'无':params.row.expLoseScore)
                  },
                  show:() => {
                    return this.hlConfig!=0
                  }
                },
                {
                  title:'加减分',
                  key:'totalAddScore',
                  align:'center',
                  tooltip:true,
                  width:60,
                  show:() => {
                    return this.hlConfig!=0
                  }
                },
                {
                  title:'攻击得分',
                  key:'attackScore',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:80,
                  show:() => {
                    return this.hlConfig==0
                  }
                },
                {
                  title:'异常得分',
                  key:'exceptScore',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:80,
                  show:() => {
                    return this.hlConfig==0
                  }
                },
                {
                  title:'防守得分',
                  key:'defendScore',
                  align:'center',
                  ellipsis:true,
                  tooltip:true,
                  width:80,
                  show:() => {
                    return this.hlConfig==0
                  }
                },
                {
                    title:'操作',
                    key:'action',
                    placement:'top-right',
                    show:() => {
                      return !(this.hlConfig==0 && !this.showAction)
                    },
                    opList:[
                      {
                        txt:'加分',
                        disabled:() => {
                          return this.disabledAllBtn
                        },
                        fun:(data) => {//4
                          if(this.showAction && this.hlConfig==0){
                            this.scoreModal.title = '团队加分';
                            this.scoreModalDkTitle = '团队加分';
                            // this.showAddsorceDk(data);
                            this.showAddsorce(data);
                          }else{
                            this.scoreModal.title = '团队加分';
                            this.showAddsorce(data);
                          }
                        }
                      },
                      {
                        txt:'减分',
                        disabled:(data) => {
                          return this.showAction && this.hlConfig==0 ? (this.disabledAllBtn || data.totalScore <= 0) : this.disabledAllBtn
                        },
                        fun:(data)=>{//3
                          if(this.showAction && this.hlConfig==0){
                            this.scoreModal.title = '团队减分';
                            this.scoreModalDkTitle = '团队减分';
                            this.showAddsorce(data)
                          }else{
                            this.scoreModal.title = '团队减分';
                            this.showAddsorce(data)
                          }
                        }
                      },
                      {
                        txt:'加减分明细',
                        show:() => {
                          return this.showAction && this.hlConfig==0
                        },
                        fun:(data)=>{
                            this.showScoreModal(data)
                        }
                      },
                    ],
                },
//              {
//                title:'异常失分',
//                key:'exceptLostScore',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//                render:(h,params)=>{
//                  return h('span', params.row.exceptLostScore||0)
//                }
//              },
//              {
//                title:'攻击总次数',
//                key:'totalCount',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//              },
//              {
//                title:'攻击成功次数',
//                key:'attackCount',
//                align:'center',
//                ellipsis:true,
//                tooltip:true,
//                render:(h,params)=>{
//                  return h('span', params.row.attackCount||0)
//                }
//              },
//              {
//                title:'防守失败次数',
//                key:'defenseFailedCount',
//                align:'center',
//                ellipsis:true,
//                render:(h,params)=>{
//                  return h('span', params.row.defenseFailedCount||0)
//                }
//              }
              ],
              listData:[]
            },
            Fnlist:'getRankingStatic',
        },
//      sencenId:'',
        selName:'',
        timeout:{},
        curPage:1,
        currentInfo:{},
        // 扣分明细
		    scoreConfigModal:false,
        columnsScore:[{
				  title:'团队名称',
				  key:'teamName',
				  align:'center',
				  ellipsis:true,
				  tooltip:true,
				  minWidth:60
		    	},{
		    		title:'加减分',
		    		key:'score',
		    		align:'center',
		    		ellipsis:true,
		    		tooltip:true,
		    		minWidth:60
		    	},{
		    		title:'动作',
		    		key:'scoreType',
		    		align:'center',
		    		ellipsis:true,
		    		tooltip:true,
		    		minWidth:60,
		    		render: (h,params)=> {
		    			let name = params.row.scoreType == 9 ? '减分':'加分';
		    			return h('span',name)
		    		}
		    	},{
		    		title:'时间',
		    		key:'startTime',
		    		align:'center',
		    		ellipsis:true,
		    		tooltip:true,
		    		minWidth:60
		    	}],
		    dataScore:[],
		    isAdd:'',
		    dataScoreTotal:0,
		    dataScorePageSize:10,
		    dataScorePageIndex:1,
      }
	},
    components:{
//    'title-top':titleTop,
      'table-body':tableBody,
    },
    watch:{
        teamList(newValue) {
            this.initObj.Select[0].optionsValue = newValue
        }
    },
    created(){
      //this.getRankingStatic();
    },
    beforeDestroy(){
		clearTimeout(this.timeout)
	},
	mounted(){
    	this.getRankingStatic();
      if(this.hlConfig==0){
        // this.initObj.Table.listCol.splice(4,6,{
        //     title:'攻击得分',
        //     key:'attackScore',
        //     align:'center',
        //     ellipsis:true,
        //     tooltip:true,
        //     width:80
        //   },
        //   {
        //     title:'异常得分',
        //     key:'exceptScore',
        //     align:'center',
        //     ellipsis:true,
        //     tooltip:true,
        //     width:80
        //   },
        //   {
        //     title:'防守得分',
        //     key:'defendScore',
        //     align:'center',
        //     ellipsis:true,
        //     tooltip:true,
        //     width:80
        //   },)
         this.initObj.Button.splice(0,2)
      }
      // if(this.hlConfig==2){
      //   this.initObj.Table.listCol.splice(2,1)
      // }
      // if(this.showAction && this.hlConfig==0){
      //   this.initObj.Table.listCol.push({
      //               title:'操作',
      //               key:'action',
      //               placement:'top-right',
      //               opList:[
      //                 {
      //                   txt:'加分',
      //                   disabled:() => {
      //                     return this.disabledAllBtn
      //                   },
      //                   on:{
      //                       click:(data)=>{//4
      //                           this.scoreModal.title = '团队加分';
      //                           this.scoreModalDkTitle = '团队加分';
      //                           // this.showAddsorceDk(data);
      //                           this.showAddsorce(data);
      //                       }
      //                   }
      //                 },
      //                 {
      //                   txt:'减分',
      //                   disabled:(data) => {
      //                     // return this.disabledAllBtn
      //                     return this.disabledAllBtn || data.totalScore <= 0
      //                   },
      //                   on:{
      //                         click:(data)=>{//3
      //                             this.scoreModal.title = '团队减分';
      //                             this.scoreModalDkTitle = '团队减分';
      //                             this.showAddsorce(data)
      //                         }
      //                     }
      //                 },
      //                 {
      //                   txt:'加减分明细',
      //                   on:{
      //                         click:(data)=>{
      //                             this.showScoreModal(data)
      //                         }
      //                     }
      //                 },
      //               ],
      //           },)
      // }
	},
  methods:{
    saveScoreRecord(){
      if(this.scoreModalDkTitle == '团队减分' && this.formValidate.score > this.currentInfo.totalScore ){
        this.$Message.warning(`团队所减分数不能大于总分，请输入${this.currentInfo.totalScore}范围内的整数`)
        return;
      }
        this.$refs['formValidate'].validate((valid) => {
            if(valid){
             if(this.showAction && this.hlConfig==0){
              if(this.scoreModalDkTitle == '团队减分'){
                this.teamScoreRecordSubDk()
              }else if(this.scoreModalDkTitle == '团队加分'){
                 this.addTeamScoreRecordAddDk()
              }
             }else{
               console.log( this.formValidate.score,' this.formValidate.score this.formValidate.score');
                this.addOrSubTO  = {
                    "sceneId":this.$route.query.id,
                    "addOrSubScore": this.scoreModal.title=='团队加分' ? this.formValidate.score :'-'+this.formValidate.score,
                    "teamId": this.teamId,
                    "partyName":this.currentInfo.partyName
                  }
                  console.log(this.addOrSubTO,'this.addOrSubTOthis.addOrSubTO');
                  addScoreRecord(this.addOrSubTO).then(data => {
                    if(data.code == 1){
                        this.$Message.info('操作成功');
                        this.scoreModal.show = false;
                        this.getRankingStatic();
                        this.handleReset('formValidate')
                    }else{
                        this.$Message.warning(data.message);
                        this.handleReset('formValidate')
                        this.scoreModal.show = false;
                    }
                }).catch(() =>{
                    this.$Message.error('操作异常')
                    this.scoreModal.show = false;
                })
             }
            }
        })

    },
    // 手动加分
    addTeamScoreRecordAddDk(){
      let data = [{
        score: this.formValidate.score,
        teamId: this.currentInfo.teamId,
        teamName: this.currentInfo.teamName,
        partyName:this.currentInfo.partyName
      }]
      teamScoreRecordAddDk(data,this.$route.query.prjid,this.$route.query.id).then(res=>{
        if(res.code == 1){
          this.handleReset('formValidate')
          this.getRankingStatic();
          this.scoreModal.show = false;
          this.$Message.info('操作成功');
        }else{
          this.handleReset('formValidate')
          this.scoreModal.show = false;
          this.$Message.warning(res.message);
        } 
      }).catch(error=>{
        this.scoreModal.show = false;
        this.$Message.error(error)
      })
    },
    // 手动减分
    teamScoreRecordSubDk(){
      let params = {
        teamName: this.currentInfo.teamName,
        partyName:this.currentInfo.partyName
      }
      let data ={
        projectId: this.$route.query.prjid,
        sceneId: this.$route.query.id,
        teamId: this.currentInfo.teamId,
        score: this.formValidate.score
      }
      teamScoreRecordSubDk(data,params).then(res=>{
        if(res.code == 1){
          this.handleReset('formValidate')
          this.getRankingStatic();
          this.scoreModal.show = false;
          this.$Message.info('操作成功');
        }else{
          this.handleReset('formValidate')
          this.scoreModal.show = false;
          this.$Message.warning(res.message);
        } 
      }).catch(error=>{
        this.scoreModal.show = false;
        this.$Message.error(error)
      })
    },

    // 扣分明细
		showScoreModal(data){
      let teamId = this.teamList.find(item => item.teamName == data.teamName).teamId
      this.currentInfo = JSON.parse(JSON.stringify(data))
      this.currentInfo.teamId = teamId
			this.getScoreConfig()
			this.isAdd = ''
			this.scoreConfigModal= true
		},
    changeScorePageSize(val){
      this.dataScorePageSize = val
      this.getScoreConfig()
    },
    changeScorePageIndex(val){
      this.dataScorePageIndex = val
      this.getScoreConfig()
    },
    // 获取扣分明细数据
		getScoreConfig(){
			let params = {
				pageIndex:this.dataScorePageIndex,
				pageSize:this.dataScorePageSize,
				sceneId:this.$route.query.id,
				teamId:this.currentInfo.teamId,
			}
			if(this.isAdd){
				params.isAdd = this.isAdd == 1 ? true :false
			}
			getSubAddListDkList(params).then(res=>{
				if (res.code ==1) {
					this.dataScore = res.data.list
					this.dataScoreTotal = res.data.total
				}else{
					this.dataScore = []
					this.dataScoreTotal = 0
					this.$Message.warning(res.message)
				}
			}).catch(error=>{
				this.dataScore = []
				this.dataScoreTotal = 0
				this.$message.error(error)
			})
		},

    showAddsorce(data){
      this.scoreModal.show=true
      // 查找 teamList 和data.teamName 匹配的 teamId
      let teamId = this.teamList.find(item => item.teamName == data.teamName).teamId
      this.teamId = data.teamId || teamId
      this.currentInfo = JSON.parse(JSON.stringify(data))
      this.currentInfo.teamId = this.teamId
      console.log('🚀 ~ this.currentInfo:', this.currentInfo)
    },
    visibleChange(type) {
        if (type) { // 打开模态框，立刻允许按钮点击
            this.scoreModal.loading = false
        } else { // 关闭模态框时，延迟使按钮点击，避免多次提交
            setTimeout(() => {
                this.scoreModal.loading = false
            }, 1000)
        }
    },
    handleReset(name) {
        this.formValidate = {
            score:1
        }
        this.$refs[name].resetFields();
    },
    exportFile(){
        let sceneId = this.$route.query.id;
        let sceneName = this.$route.query.name; 
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = `/api/compete/teamScoreRecord/exportNewRb/${sceneId}/${sceneName}`;
        a.download = ''; //命名下载名称
        a.click(); //点击触发下载
        a.remove();
    },
    exportScoreRecord(){
		  let sceneId = this.$route.query.id;
	  	let sceneName = this.$route.query.name;
	  	let a = document.createElement("a");
	    document.body.appendChild(a);
	    a.href = `/api/compete/userSubmitRecord/export/${sceneId}/${sceneName}`;
	    a.download = ''; //命名下载名称
	    a.click(); //点击触发下载
	    a.remove();
	},
    downloadAllReport(){
        let sceneId = this.$route.query.id;
        downloadSceneAllReport(sceneId,[],).then(data => {
            this.total = 0
            if(data.type == 'application/octet-stream'){
                const downloadElement = document.createElement("a");
                const href = window.URL.createObjectURL(data);
                downloadElement.href = href;
                downloadElement.download = '解题报告.zip';
                document.body.appendChild(downloadElement);
                downloadElement.click();
                document.body.removeChild(downloadElement); // 下载完成移除元素
                window.URL.revokeObjectURL(href); // 释放掉blob对象
            }else{
                this.$Message.error('下载报告失败!不存在文件数据！');
            }
        }).catch(error => {
            this.progressStatus = 'wrong'
            this.$Message.error('下载报告失败!');
        }).finally(() => {
            this.progress = 100
            setTimeout(() => {
                this.showProgress = false
                this.progressStatus = 'active'
                this.progress = 0
            }, 2000)
        })
    },
    getRankingById(id) {
      this.selName = this.getTeamNameById(id);
      this.getRankingStatic();
    },
    getRankingStatic(page,pageSize,querytime){
      let _this = this;
      let pages = page || 1;
      this.$set(this.initObj.Page, 'currentPage', pages)
      let rows = pageSize||_this.PZ|| 10;
      let id = '';
      let params={
        pageIndex : pages,
        pageSize : rows
      };
      this.curPage = pages;
      if(this.selName){
        params.teamName =  this.selName;
      }
      if(_this.$route.query.id){
        teamRankStatic(this.$route.query.id,params).then(data=>{
          if(data.code==1){
            _this.initObj.Table.listData = data.data.items;
            _this.initObj.Page.total = data.data.total;
            clearTimeout(this.timeout)
            if(this.poll){ //如果需要轮询
            	this.timeout = setTimeout(() => {
            		this.getRankingStatic(page, pageSize);
            	},3000)
            }
          }
        })
      }
    },
    saveInfo(val){
    }
    },
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
  .Titles{
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
  }
  .targetHeader{
    padding: 10px;
    margin-bottom: 10px;
  }
</style>
